import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import type { RouteMapItem } from '@/types/vue-router'
import route from './route.json?raw'
import NProgress from './nprogress'
import { useButtonStore, useMenuStore, useUserStore } from '@/stores'
import { refresh } from '@/services/auth'

export const getRouteMap = () => {
  return JSON.parse(route) as RouteMapItem
}

const modules = import.meta.glob('@/views/**/*View.vue')

export const getImportComponent = (path: string) => {
  return modules[`/src/views/${path}.vue`]
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: () => import('@/layouts/DefaultLayout.vue'),
      redirect: { name: 'home' },
      children: [
        {
          path: 'home',
          name: 'home',
          component: getImportComponent('HomeView'),
          meta: {
            enterActiveClass: 'animate__animated animate__fadeInRight',
            leaveActiveClass: 'animate__animated animate__fadeOutRight'
          }
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: getImportComponent('LoginView')
    }
  ]
})

// guard
router.beforeEach(async (to) => {
  NProgress.start()

  const userStore = useUserStore()
  const isLogin = userStore.isLogin()
  const isLoginView = to.name === 'login'
  if (!isLogin && isLoginView) {
    return true
  } else if (isLogin && isLoginView) {
    return { name: 'home' }
  } else if (!isLogin && !isLoginView) {
    return { name: 'login' }
  }
  if (!userStore.isAddRouter) {
    userStore.isAddRouter = true
    refresh()
    const menuStore = useMenuStore()
    const buttonStore = useButtonStore()
    menuStore.menuRoutes.forEach(({ name, full }) => addRoute(name, full))
    buttonStore.buttonRoutes.forEach(({ name, full }) => addRoute(name, full))
    // 这里必须使用 path，因为这里才动态添加或者删除路由，可能已经匹配到 NotFound 路由了，只有 path 是正确的，重新跳转下就可以了
    return { ...to, replace: true }
  }
})
router.onError(() => NProgress.done())
router.afterEach(() => NProgress.done())

export default router

// 判断 menu 中的路由 name 是否已经动态注册，未动态注册则注册
export const routeMap = getRouteMap()
export const addRoute = (name: string, full: boolean) => {
  if (!router.hasRoute(name) && routeMap[name]) {
    const { path, component } = routeMap[name]
    if (!component || !path) {
      return
    }
    const view = getImportComponent(component)
    if (!view) {
      return
    }
    const route: RouteRecordRaw = {
      path,
      name,
      component: view
    }
    if (full) {
      router.addRoute(route)
    } else {
      router.addRoute('layout', route)
    }
  }
}
